# -*- coding: utf-8 -*-
# @Time    : 2024/8/29 0:34
# @Author  : Alvin
# @File    : error.py
from flask import request, json
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500
    msg = '服务器开小差~'
    error_code = 999

    def __init__(self, code=None, msg=None, error_code=None):
        if code:
            self.code = code
        if msg:
            self.msg = msg
        if error_code:
            self.error_code = error_code
        super(APIException, self).__init__(msg, response=None)

    def get_body(self, environ=None, scope=None):
        body = dict(
            msg=self.msg,
            error_code=self.error_code,
            request=request.method + ' ' + self.get_url_no_params()
        )
        text = json.dumps(body)
        return text

    def get_headers(self, environ=None, scope=None):
        """Get a list of headers."""
        return [('Content-Type', 'application/json')]

    '''
    eg:
    http://example.com/foo?bar=baz
    request.full_path -> /foo?bar=baz
    '''

    @staticmethod
    def get_url_no_params():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
